﻿using System;
using System.Collections.Generic;
using System.Text;
using RegionInterface;
using Common;
using UnityEngine;

public class MonsterModule : ModuleBase, IMonsterModule
{
    public List<MonsterHandle> Monsters;
    public MonsterModule()
    {
        Monsters = new List<MonsterHandle>();
        AppInterface.MonsterModule = this as IMonsterModule;
        RegionStateManager.LoginStateChangeHandle += delegate(LoginState form, LoginState to)
        {
            if (to == LoginState.LoginEnd)
            {
                setMonster();
            }
            if (to == LoginState.LogoutEnd)
            {
                
            }
        };
    }
    private void setMonster()
    {
        GameObject root = GameObject.Find("scene001/scene001/Enemies");
        for (int i = 0; i < root.transform.childCount; i++)
        {
            GameObject tmp = GameObject.Instantiate(Resources.Load("Monster/" + root.transform.GetChild(i).name)) as GameObject;
            tmp.transform.position = root.transform.GetChild(i).position;
            MonsterHandle handle = new MonsterHandle(this, tmp.transform, i);
            Monsters.Add(handle);
            AddMonster(handle as IUnit);
        }
    }

    public override void Update()
    {
        foreach (MonsterHandle p in Monsters)
        {
            if(!p.Dead) p.Update();
        }
    }
    public override void FixedUpdate()
    {
        int deleteId = -1;
        for (int i = 0; i < Monsters.Count; i++)
        {
            if (Monsters[i].Dead) deleteId = i;
            else Monsters[i].FixedUpdate();
        }
        if (deleteId > -1)
        {
            DeleteMonster(Monsters[deleteId]);
            Monsters.RemoveAt(deleteId);
        }
    }
    public void DeleteFromlive(MonsterHandle m)
    {
        int deleteId = -1;
        for (int i = 0; i < liveMonster.Count; i++)
        {
            if (liveMonster[i].Id == m.Id)
            {
                deleteId = i;
                break;
            }
        }
        if (deleteId > -1)
        {
            liveMonster.RemoveAt(deleteId);
        }
    }
    public void AddTolive(MonsterHandle m)
    {
        liveMonster.Add(m);
    }
    #region IMonsterModule Members
    private List<IUnit> liveMonster = new List<IUnit>();
    public List<IUnit> LiveMonster
    {
        get 
        {
            return liveMonster;
        }
    }

    public event Action<IUnit> OnAddMonster;
    private void AddMonster(IUnit unit)
    {
        if (OnAddMonster != null) OnAddMonster(unit);
    }
    public event Action<IUnit> OnDeleteMonster;
    private void DeleteMonster(IUnit unit)
    {
        if (OnDeleteMonster != null) OnDeleteMonster(unit);
    }
    #endregion
}
